package com.example.service;

import com.example.model.Permission;
import com.example.repository.PermissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {
    
    @Autowired
    private PermissionRepository permissionRepository;
    
    @Override
    public Permission createPermission(Permission permission) {
        if (existsByCode(permission.getCode())) {
            throw new RuntimeException("权限代码已存在: " + permission.getCode());
        }
        if (existsByName(permission.getName())) {
            throw new RuntimeException("权限名称已存在: " + permission.getName());
        }
        return permissionRepository.save(permission);
    }
    
    @Override
    public Permission updatePermission(Permission permission) {
        if (!permissionRepository.existsById(permission.getId())) {
            throw new RuntimeException("权限不存在");
        }
        
        // 检查代码和名称是否与其他权限冲突
        Optional<Permission> existingByCode = permissionRepository.findByCode(permission.getCode());
        if (existingByCode.isPresent() && !existingByCode.get().getId().equals(permission.getId())) {
            throw new RuntimeException("权限代码已存在: " + permission.getCode());
        }
        
        Optional<Permission> existingByName = permissionRepository.findByName(permission.getName());
        if (existingByName.isPresent() && !existingByName.get().getId().equals(permission.getId())) {
            throw new RuntimeException("权限名称已存在: " + permission.getName());
        }
        
        return permissionRepository.save(permission);
    }
    
    @Override
    public void deletePermission(Long id) {
        if (!canDeletePermission(id)) {
            throw new RuntimeException("该权限不能删除");
        }
        permissionRepository.deleteById(id);
    }
    
    @Override
    public Optional<Permission> findById(Long id) {
        return permissionRepository.findById(id);
    }
    
    @Override
    public Optional<Permission> findByCode(String code) {
        return permissionRepository.findByCode(code);
    }
    
    @Override
    public Optional<Permission> findByName(String name) {
        return permissionRepository.findByName(name);
    }
    
    @Override
    public List<Permission> findAllActivePermissions() {
        return permissionRepository.findByIsActiveTrueOrderByModule();
    }
    
    @Override
    public Page<Permission> findAllActivePermissions(Pageable pageable) {
        return permissionRepository.findByIsActiveTrue(pageable);
    }
    
    @Override
    public List<Permission> findByModule(String module) {
        return permissionRepository.findByModuleAndIsActiveTrue(module);
    }
    
    @Override
    public List<Permission> findByType(Permission.PermissionType type) {
        return permissionRepository.findByTypeAndIsActiveTrue(type);
    }
    
    @Override
    public List<Permission> findSystemPermissions() {
        return permissionRepository.findByIsSystemTrue();
    }
    
    @Override
    public List<Permission> findNonSystemPermissions() {
        return permissionRepository.findByIsSystemFalse();
    }
    
    @Override
    public List<Permission> searchPermissionsByName(String name) {
        return permissionRepository.findByNameContainingAndIsActiveTrue(name);
    }
    
    @Override
    public Permission activatePermission(Long id) {
        Optional<Permission> permissionOpt = permissionRepository.findById(id);
        if (permissionOpt.isPresent()) {
            Permission permission = permissionOpt.get();
            permission.setIsActive(true);
            return permissionRepository.save(permission);
        }
        throw new RuntimeException("权限不存在");
    }
    
    @Override
    public Permission deactivatePermission(Long id) {
        Optional<Permission> permissionOpt = permissionRepository.findById(id);
        if (permissionOpt.isPresent()) {
            Permission permission = permissionOpt.get();
            if (permission.getIsSystem()) {
                throw new RuntimeException("系统权限不能停用");
            }
            permission.setIsActive(false);
            return permissionRepository.save(permission);
        }
        throw new RuntimeException("权限不存在");
    }
    
    @Override
    public PermissionStatistics getPermissionStatistics() {
        Long totalPermissions = permissionRepository.count();
        Long activePermissions = (long) permissionRepository.findByIsActiveTrueOrderByModule().size();
        Long systemPermissions = (long) permissionRepository.findByIsSystemTrue().size();
        Long customPermissions = totalPermissions - systemPermissions;
        
        // 统计各类型权限数量
        List<Object[]> typeStats = permissionRepository.countByType();
        Long menuPermissions = 0L, buttonPermissions = 0L, apiPermissions = 0L, dataPermissions = 0L;
        
        for (Object[] stat : typeStats) {
            Permission.PermissionType type = (Permission.PermissionType) stat[0];
            Long count = (Long) stat[1];
            switch (type) {
                case MENU: menuPermissions = count; break;
                case BUTTON: buttonPermissions = count; break;
                case API: apiPermissions = count; break;
                case DATA: dataPermissions = count; break;
            }
        }
        
        return new PermissionStatistics(totalPermissions, activePermissions, systemPermissions, 
                                      customPermissions, menuPermissions, buttonPermissions, 
                                      apiPermissions, dataPermissions);
    }
    
    @Override
    public List<Object[]> getPermissionsByModule() {
        return permissionRepository.countByModule();
    }
    
    @Override
    public List<Object[]> getPermissionsByType() {
        return permissionRepository.countByType();
    }
    
    @Override
    public boolean existsByCode(String code) {
        return permissionRepository.findByCode(code).isPresent();
    }
    
    @Override
    public boolean existsByName(String name) {
        return permissionRepository.findByName(name).isPresent();
    }
    
    @Override
    public boolean canDeletePermission(Long id) {
        Optional<Permission> permissionOpt = permissionRepository.findById(id);
        if (permissionOpt.isPresent()) {
            Permission permission = permissionOpt.get();
            // 系统权限不能删除
            return !permission.getIsSystem();
        }
        return false;
    }
}
